import Rte from 'editor/index'
import { ParagraphStylePropties, RteInputReactiveMap, RteInputRefs, TextStylePropties } from './declare'
import RteIssets from './issets'
import { RenderInst } from 'share/declare'
import render from 'share/render'
import { reactive, ReactiveInstance } from 'share/reactive'

import 'assets/style/input.scss'
import ast from '!!html-ast-loader!./input.html'
import { last, textSplit } from 'share/utils'
import RteLine from 'content/line/line'
import onCaretInput from './module/inputevent'
import { onCaretComposition } from './module/composition'

export default class RteInput implements RenderInst {
  // @ts-ignore
  public $refs: RteInputRefs = {}

  public $data: ReactiveInstance<RteInputReactiveMap>

  public text = new RteIssets(TextStylePropties)

  public paragrap = new RteIssets(ParagraphStylePropties)

  public constructor(public editor: Rte) {
    this.$data = reactive({ showlist: false })

    render(ast, this)

    editor.$moniter.$once('mounted', () => {
      onCaretInput(editor)
      onCaretComposition(editor)

      const lastLine = last(editor.content.line)
      if (lastLine instanceof RteLine) {
        lastLine.caretIn()
      }
    })
  }

  public focus() {
    this.$refs.caret.focus()
    return this
  }

  public blur() {
    this.insertText()
    this.$refs.root.remove()
    this.text.clear()
    this.paragrap.clear()
    return this
  }

  /**
   * 展示输入提示（Markdown语法，@功能）
   */
  public toolList() {}

  /**
   * 删除选区内容
   */
  public deleteSelection() {}

  /**
   * 普通的文字输入
   */
  public insertText() {
    const { root, caret } = this.$refs
    const text = caret.innerText
    if (text.length) {
      const style = this.text.cssText()
      const html = textSplit(text)
        .map((char) => `<span style="${style}">${char.char}</span>`)
        .join('')
      root.insertAdjacentHTML('beforebegin', html)
      caret.innerText = ''
    }
  }
}
